package com.roger.myHome.importDemo;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//https://www.cnblogs.com/JavaBuild/p/18185854
@Component
@Slf4j
public class UserDataListener extends AnalysisEventListener<UserImportDTO> {

    private final ExecutorService executor = Executors.newFixedThreadPool(8);

    private final List<UserImportDTO> batch = new ArrayList<>();

    /*单次处理条数*/
    private final static int BATCH_COUNT = 1000;


    @Override
    public void invoke(UserImportDTO dto, AnalysisContext context) {
        //System.out.println("");
        System.out.println(dto.getName() + ":" + dto.getPhone());
        batch.add(dto);
        if (batch.size() >= BATCH_COUNT) {
            saveBatch();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        System.out.println("do after");
        System.out.println(batch);
        if (!batch.isEmpty()) {
            //saveBatch();
        }
    }

    private void saveBatch() {
        List<UserImportDTO> copy = new ArrayList<>(batch);
        batch.clear();
        CompletableFuture.runAsync(() -> {
            //userService.saveBatch(copy);
        }, executor);

    }
}
